import { defineStore } from "pinia"
import http from "../utils/http"


export const useLogin = defineStore("login", {
    state: () => {
        return {
            userobj: JSON.parse(localStorage.getItem("users")||'{}'),
            issign:"",
            token:localStorage.getItem("token")||"",
        }
    },
    actions: {
        //登录
        async getuser(obj) {
            let res = await http.post("/api/auth/login",{
                name:obj.name,
                password: obj.password,
            })
            if(res.status==200&&res.data.statusCode==200){
                this.userobj = {...res.data.data}
                this.token = res.data.data.token
                localStorage.setItem("token",this.token)
                localStorage.setItem("users",JSON.stringify(this.userobj))
            }
        },
        //注册
        async signuser(obj){
          try {
            let res = await http.post("/api/user/register",{
                name:obj.username,
                password:obj.password,
                role:"admin"
            })
            console.log(res,"res")
          if(res.status===201){
            this.issign="注册成功"
          }else{
            this.issign="注册失败"
          }
          } catch (error) {
            console.log(error)
            this.issign="注册失败"
          }
        },
        //更新用户信息
        async editusers(obj){
          let res = await http.post("/api/user/update",obj);
          console.log(res,"res userinfo")
          if(res.status==201){
            this.userobj = {...res.data.data}
            this.token = res.data.data.token
            localStorage.setItem("token",this.token)
            localStorage.setItem("users",JSON.stringify(this.userobj))
          }
        }
    },
    getters: {

    }
})